package org.qiancizhan.Mapper;

import com.google.gson.Gson;
import org.qiancizhan.Config.MySQL;
import org.qiancizhan.Config.RedisConfig;
import org.qiancizhan.Model.DTO.AIConversationContentDTO;
import org.qiancizhan.Model.POJO.AIConversationContentPOJO;
import org.qiancizhan.Model.POJO.AIConversationPOJO;
import org.qiancizhan.Model.POJO.UserPOJO;
import org.qiancizhan.Utils.RandomIDGenerateUtil;
import org.qiancizhan.Utils.ThreadLocalUtil;
import redis.clients.jedis.Jedis;

import java.util.List;

public class AIConversationMapper {
    private final Jedis redis = RedisConfig.getInstance();
    private final MySQL mySQL = MySQL.getInstance();
    private final Gson gson = new Gson();

    public String addAIConversation(boolean isXiaoAi, String title, int messageCount) {
        String conversationId = RandomIDGenerateUtil.generateRandomID();
        UserPOJO user = ThreadLocalUtil.get();
        mySQL.executeUpdate(
                """
                INSERT INTO `ai_conversation` (`id`, `fk_users_id`, `is_xiao_ai`, `title`, `message_count`, `created_at`, `updated_at`)
                VALUES (?, ?, ?, ?, ?, NOW(), NOW());
                """,
                conversationId, user.getId(), isXiaoAi ? 1 : 0, title, messageCount
        );
        return conversationId;
    }


    public List<AIConversationPOJO> getUserAIConversationList() {
        UserPOJO user = ThreadLocalUtil.get();
        List<AIConversationPOJO> userConversationList = mySQL.executeQuery(
                String.format("""
                        SELECT ac.* FROM `ai_conversation` ac
                        WHERE ac.fk_users_id = %d;
                        """, user.getId())
                , rs -> {
                    AIConversationPOJO conversation = new AIConversationPOJO();
                    conversation.setId(rs.getString("id"));
                    conversation.setFk_users_id(rs.getInt("fk_users_id"));
                    conversation.setIsXiaoAi(rs.getInt("is_xiao_ai"));
                    conversation.setTitle(rs.getString("title"));
                    conversation.setMessage_count(rs.getInt("message_count"));
                    conversation.setCreated_at(rs.getTimestamp("created_at"));
                    conversation.setUpdated_at(rs.getTimestamp("updated_at"));
                    return conversation;
                }
        );
        return userConversationList.size() > 0 ? userConversationList : null;
    }

    public List<AIConversationContentPOJO> getUserAIConversationContents(String conversationId) {
        UserPOJO user = ThreadLocalUtil.get();
        List<AIConversationContentPOJO> userMessages = mySQL.executeQuery(
                String.format("""
                        SELECT acc.* FROM `ai_conversation_content` acc
                        JOIN ai_conversation ac ON acc.fk_conversation_id = ac.id
                        JOIN users ON users.id = ac.fk_users_id
                        WHERE ac.fk_users_id = %d AND acc.fk_conversation_id = '%s';""", user.getId(), conversationId)
                , rs -> {
                    AIConversationContentPOJO message = new AIConversationContentPOJO();
                    message.setId(rs.getString("id"));
                    message.setFk_conversation_id(rs.getString("fk_conversation_id"));
                    message.setMessage_type(rs.getString("message_type"));
                    message.setMessage_content(rs.getString("message_content"));
                    message.setCreated_at(rs.getTimestamp("created_at"));
                    return message;
                }
        );
        return userMessages.size() > 0 ? userMessages : null;
    }


    public void addAIcontent(String conversationID, List<AIConversationContentDTO> messages) {
        for (AIConversationContentDTO message : messages) {
            mySQL.executeUpdate(
                    """
                    INSERT INTO `ai_conversation_content` (`id`, `fk_conversation_id`, `message_type`, `message_content`, `created_at`)
                    VALUES (?, ?, ?, ?, NOW());
                    """,
                    message.getId(),
                    conversationID,
                    message.getMessage_type(),
                    message.getMessage_content()
            );
        }
    }

    public void clearConversation() {
        UserPOJO user = ThreadLocalUtil.get();
        mySQL.executeUpdate(
                """
                DELETE FROM `ai_conversation`
                WHERE fk_users_id = ?;
                """,
                user.getId()
        );
    }
}
